package com.hllxd.hism.star.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;

@Slf4j
public class ResultUtils {
    private static String hostName;
    static {
        try {
            hostName = InetAddress.getLocalHost().getHostName();
        }catch (Exception e) {
            hostName = "unknown";
        }
    }
    public static JSONObject errorResult(String code,String message) {
        ConsoleContext context = ThreadLocalManager.getConsoleContext();
        JSONObject result = new JSONObject();
        if(null != context){
            result.put("ms", System.currentTimeMillis() - context.getBeginMs());
            result.put("traceID", context.getTraceId());
            result.put("groupID", context.getGroupId());
        }else {
            log.warn("context is nil.");
        }
        result.put("code", code);
        result.put("message", message);
        result.put("success", "false");
        result.put("host",hostName);
        return result;
    }

    public static JSONObject result(Object object) {
        ConsoleContext context = ThreadLocalManager.getConsoleContext();
        JSONObject result = new JSONObject();
        if(null != context){
            result.put("ms", System.currentTimeMillis() - context.getBeginMs());
            result.put("traceID", context.getTraceId());
            result.put("groupID", context.getGroupId());
        }else {
            log.warn("context is nil.");
        }
        result.put("code", "000");
        result.put("message", "");
        result.put("success", "true");
        result.put("host",hostName);
        result.put("data", object);
        return result;
    }

    public static JSONObject result(String code, String message, Object object) {
        ConsoleContext context = ThreadLocalManager.getConsoleContext();
        JSONObject result = new JSONObject();
        if(null != context){
            result.put("ms", System.currentTimeMillis() - context.getBeginMs());
            result.put("traceID", context.getTraceId());
            result.put("groupID", context.getGroupId());
        }else {
            log.warn("context is nil.");
        }
        result.put("code", code);
        result.put("message", message);
        String successCode="000";
        result.put("success", code.equals(successCode)?"true":"false");
        result.put("host",hostName);
        result.put("data", object);
        return result;
    }

}
